package com.rzjm.api.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.lock.LockInfo;
import com.baomidou.lock.LockTemplate;
import com.baomidou.lock.executor.RedissonLockExecutor;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rzjm.api.constant.ResponseCode;
import com.rzjm.api.entity.*;
import com.rzjm.api.service.*;
import com.rzjm.api.util.DateUtil;
import com.rzjm.api.util.GsonResultBean;
import com.rzjm.api.util.OssUtil;
import com.rzjm.api.util.Tools;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

/**
 *@Author: ZhouWei
 *@Description:  动火作业
 *@Date 2018-05-10
 */
@Component
@RestController
@RequestMapping("/fire/work")//url:模块/资源/{}/细分
public class FireWorkController extends BaseController {

    @Resource
    private UserService userService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private FireWorkService fireWorkService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private FireWorkUserService fireWorkUserService;
    @Resource
    private FireSafetyMeasuresService safetyMeasuresService;
    @Resource
    private FireWorkAnalysisService workAnalysisService;
    @Resource
    private FireWorkMeasuresService workMeasuresService;
    @Resource
    private WxTemplateService wxTemplateService;
    @Resource
    private FireWorkImgService fireWorkImgService;
    @Resource
    private DeviceWeldingService deviceWeldingService;
    @Resource
    private DeviceWeldingRecordService deviceWeldingRecordService;
    @Resource
    private FsrDeviceService fsrDeviceService;
    @Resource
    private ShopService shopService;

    @Resource
    private LockTemplate lockTemplate;


    @Value("${web.uploadPath}")
    private String uploadPath;//图片地址

    @Value("${web.imgprefix}")
    private String imgPrefix;//图片地址

    /**
     *  制度列表
     * @param
     * @throws Exception
     */
    @PostMapping(value = "/test")
    public JSONObject test(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            logBefore(logger, "fire/work/view 接收的参数： "+requestParam);
            System.out.println("fire/work/view 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int record_type = jsonRequest.containsKey("record_type") ? jsonRequest.getInt("record_type") : 0;

            FireWork fireWork = fireWorkService.findById(115);

            wxTemplateService.sendWxMsgRegFireWork(fireWork, new ArrayList<>());

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);

        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  制度列表
     * @param
     * @throws Exception
     */
    @PostMapping(value = "/view")
    public JSONObject view(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            logBefore(logger, "fire/work/view 接收的参数： "+requestParam);
            System.out.println("fire/work/view 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int record_type = jsonRequest.containsKey("record_type") ? jsonRequest.getInt("record_type") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            SysUser sysUser = sysUserService.selectByUniqueColumn("user_id",user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您没有该权限"),true,true);
            }

            Shop shop = shopService.findById(sysUser.getShopId());
            if(shop == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定企业"),true,true);
            }

            if(shop.getState() == 0){
                System.out.println(shop.getShopName() + " 企业已被禁用");
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
            }


            map.put("shop",shop);

            map.put("is_submit", 0);

            //最后批准人   片区管理员
            QueryWrapper<SysUser> qwPianquUser = new QueryWrapper<>();
            qwPianquUser.eq("pianqu_id", shop.getPianquId());
            qwPianquUser.eq("user_type",3);
            qwPianquUser.last("limit 1");
            SysUser sysUserLastSubmit = sysUserService.getOne(qwPianquUser);
            if(sysUserLastSubmit!= null){
                if(sysUser.getUserId().intValue() == sysUserLastSubmit.getUserId().intValue()){
                    map.put("is_submit", 1);
                }
            }

//            if(sysUser.getUserId().intValue() == shop.getLastSubmitSysUserId().intValue()){
//                map.put("is_submit", 1);
//            }

//            本企业的电焊部门
//            QueryWrapper<Department> qwDept = new QueryWrapper<>();
//            qwDept.eq("company_id", sysUser.getShopId());
//            if(record_type == 0){
//                qwDept.eq("dept_type", 2);
//            } else if(record_type == 2){
//                qwDept.eq("dept_type", 3);
//            }
//            qwDept.last("limit 1");
//            Department department = departmentService.getOne(qwDept);
//            if(department == null){
//                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"没有该部门"),true,true);
//            }
            QueryWrapper<SysUser> qwWorker = new QueryWrapper<>();
            qwWorker.eq("shop_id", sysUser.getShopId());
            if(record_type == 0){
//                qwWorker.eq("dept_id",department.getId());
                qwWorker.isNotNull("certificate_num");
                qwWorker.ne("certificate_num","");
            }else if(record_type == 2){
                qwWorker.isNotNull("high_cert_num");
                qwWorker.ne("high_cert_num","");
            }
            qwWorker.eq("role_id", 12);
            qwWorker.eq("status", 1);
            List<SysUser> workUsers = sysUserService.list(qwWorker);
            map.put("workUsers",workUsers);


            QueryWrapper<FireSafetyMeasures> qw = new QueryWrapper<>();
            qw.eq("measures_type",record_type);
            qw.orderByAsc("sort");
            List<FireSafetyMeasures> safetyMeasures = safetyMeasuresService.list(qw);

            map.put("measures",safetyMeasures);


            List<Map<String,Object>> sysUserActions = new ArrayList<>();
            List<String> userNames = new ArrayList<>();
            QueryWrapper<SysUser> qwTable = new QueryWrapper<>();
            qwTable.eq("shop_id", sysUser.getShopId());
            qwTable.eq("status", 1);
            List<SysUser> sysUserList = sysUserService.list(qwTable);
            if(CollUtil.isNotEmpty(sysUserList)){
                for (SysUser sysUser1 : sysUserList){
                    Map<String,Object> sheetOption = new HashMap<>();
                    sheetOption.put("sys_user_id", sysUser1.getUserId());
                    sheetOption.put("name", sysUser1.getName());
                    Department department1 = departmentService.findById(sysUser1.getDeptId());
                    if(department1!= null){
                        sheetOption.put("subname", department1.getName());
                        userNames.add(sysUser1.getName() + " - " + department1.getName());

                        sysUser1.setDeptName(department1.getName());

                    }
                    sheetOption.put("color","#1989fa");
                    sysUserActions.add(sheetOption);

                }
            }
            map.put("userActions",sysUserActions);
            map.put("userNames",userNames);
            map.put("sysUserList",sysUserList);


            map.put("workHeightMin",4);
            map.put("workHeightMax",40);

            Department safeDept = departmentService.getSafeDepart(sysUser.getShopId());
            if(safeDept != null){
                QueryWrapper<SysUser> qwSafe = new QueryWrapper<>();
                qwSafe.eq("shop_id", sysUser.getShopId());
                qwSafe.eq("dept_id", safeDept.getId());
                qwSafe.eq("status", 1);
                List<SysUser> safeUser = sysUserService.list(qwSafe);
                map.put("safeUserList",safeUser);
            }

            map.put("sysUser",sysUser);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);

        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  添加作业申请
     * @param
     * @throws Exception
     */
    @PostMapping(value="/add/record")
    public JSONObject addRecord(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;

        logBefore(logger, "fire/work/add/record 接收的参数： " + requestParam);
        System.out.println("fire/work/add/record 接收的参数： " + requestParam);
        JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
        int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;

        LockInfo lockInfo = lockTemplate.lock(user_id + "_addFireWorkRecord", 30000L, 5000L, RedissonLockExecutor.class);
        if (lockInfo == null) {
            return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"业务处理中,请稍后再试"),true,true);
        }

        try{
            String dataJson = jsonRequest.containsKey("data_json") ? jsonRequest.getStr("data_json") : null;
            String workerResult = jsonRequest.containsKey("worker_result") ? jsonRequest.getStr("worker_result") : null;
            String outWorkerList = jsonRequest.containsKey("out_worker") ? jsonRequest.getStr("out_worker") : null;
            String signImg = jsonRequest.containsKey("sign_img") ? jsonRequest.getStr("sign_img") : null;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            SysUser sysUser = sysUserService.selectByUniqueColumn("user_id",user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您没有该权限"),true,true);
            }


            Shop shop = shopService.findById(user.getShopId());
            if(shop.getState() == 0){
                System.out.println(shop.getShopName() + " 企业已被禁用");
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
            }

            FireWork fireWork = JSONUtil.toBean(dataJson, FireWork.class);

            fireWork.setRegSignImg(signImg);

            fireWork.setUserId(user_id);
            int ret = fireWorkService.addWorkRecord(fireWork,outWorkerList,workerResult);
            if(ret > 0){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功"),true,true);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"成功"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  添加作业申请(中慧集团 逻辑 )
     * @param
     * @throws Exception
     */
    @PostMapping(value="/add/record/zh")
    public JSONObject addRecordZh(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        logBefore(logger, "fire/work/add/record 接收的参数： "+requestParam);
        System.out.println("fire/work/add/record 接收的参数： "+requestParam);
        JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
        int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;

        LockInfo lockInfo = lockTemplate.lock(user_id + "_addRecordZh", 30000L, 5000L, RedissonLockExecutor.class);
        if (lockInfo == null) {
            return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"业务处理中,请稍后再试"),true,true);
        }

        try{
            String dataJson = jsonRequest.containsKey("data_json") ? jsonRequest.getStr("data_json") : null;
            String workerResult = jsonRequest.containsKey("worker_result") ? jsonRequest.getStr("worker_result") : null;
            String outWorkerList = jsonRequest.containsKey("out_worker") ? jsonRequest.getStr("out_worker") : null;
            String signImg = jsonRequest.containsKey("sign_img") ? jsonRequest.getStr("sign_img") : null;



            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            SysUser sysUser = sysUserService.selectByUniqueColumn("user_id",user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您没有该权限"),true,true);
            }


            Shop shop = shopService.findById(user.getShopId());
            if(shop.getState() == 0){
                System.out.println(shop.getShopName() + " 企业已被禁用");
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
            }

            FireWork fireWork = JSONUtil.toBean(dataJson, FireWork.class);

            fireWork.setRegSignImg(signImg);

            fireWork.setUserId(user_id);
            int ret = fireWorkService.addWorkRecord(fireWork,outWorkerList,workerResult);
            if(ret > 0){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功"),true,true);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"成功"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }finally {
            //释放锁
            lockTemplate.releaseLock(lockInfo);
        }
        return result;
    }

    /**
     *  制度列表
     * @param
     * @throws Exception
     */
    @PostMapping(value = "/detail")
    public JSONObject detail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            logBefore(logger, "fire/work/view 接收的参数： "+requestParam);
            System.out.println("fire/work/detail 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int workId = jsonRequest.containsKey("work_id") ? jsonRequest.getInt("work_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }



            Shop shopUser = shopService.findById(user.getShopId());
            if(shopUser.getState() == 0){
                System.out.println(shopUser.getShopName() + " 企业已被禁用");
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
            }

            SysUser sysUser = sysUserService.selectByUniqueColumn("user_id",user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您没有该权限"),true,true);
            }
            Shop shop = null;
            if(sysUser.getUserType() == 10){
                shop = shopService.findById(sysUser.getShopId());
                if(shop == null){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定企业"),true,true);
                }
                map.put("shop",shop);
            }

            map.put("is_submit", 0);

            //最后批准人   片区管理员
            QueryWrapper<SysUser> qwPianquUser = new QueryWrapper<>();
            if(shop!= null){
                qwPianquUser.eq("pianqu_id", shop.getPianquId());
            }else{
                qwPianquUser.eq("pianqu_id", sysUser.getPianquId());
            }
            qwPianquUser.eq("user_type",3);
            qwPianquUser.last("limit 1");
            SysUser sysUserLastSubmit = sysUserService.getOne(qwPianquUser);
            if(sysUserLastSubmit != null){
                if(sysUser.getUserId().intValue() == sysUserLastSubmit.getUserId().intValue()){
                    map.put("is_submit", 1);
                }
            }


            FireWork fireWork = fireWorkService.findById(workId);
            if(fireWork != null){

                QueryWrapper<FireWorkAnalysis> qwAnalysis = new QueryWrapper<>();
                qwAnalysis.eq("fire_work_id",workId);
                List<FireWorkAnalysis> analyses = workAnalysisService.list(qwAnalysis);
                fireWork.setAnalyses(analyses);


                //{天, 时, 分, 秒}
                long[] times = DateUtil.getDistanceTimes(fireWork.getFireBeginTime(),fireWork.getFireEndTime());
                String workTimes = "";
                if(times[0] > 0){
                    workTimes += times[0] + "天";
                }
                if(times[1] > 0){
                    workTimes += times[1] + "小时";
                }
                if(times[2] > 0){
                    workTimes += times[2] + "分钟";
                }
                fireWork.setWorkTimes(workTimes);


                QueryWrapper<FireWorkMeasures> qwMeasure = new QueryWrapper<>();
                qwMeasure.eq("fire_work_id",workId);
                List<Integer> opTypes = new ArrayList<>();

                if(fireWork.getSafeSysUserId()!= null && fireWork.getSafeSysUserId().intValue() == sysUser.getUserId().intValue()){
//                    qwMeasure.eq("op_type", 0);
                    opTypes.add(0);
                    map.put("user_type","safe");
                }
//                if(fireWork.getHeaderSysUserId()!= null && fireWork.getHeaderSysUserId().intValue() == sysUser.getUserId().intValue()){
////                    qwMeasure.eq("op_type", 1);
//                    opTypes.add(1);
//                    map.put("user_type","header");
//                }
                if(opTypes.size() > 0){
                    qwMeasure.in("op_type", opTypes);
                }

                List<FireWorkMeasures> workMeasures = workMeasuresService.list(qwMeasure);
                fireWork.setMeasures(workMeasures);

                List<FireWorkUser> workUsers = fireWorkUserService.selectListByColumn("fire_work_id", fireWork.getId());
                fireWork.setWorkUsers(workUsers);


                QueryWrapper<FireWorkImg> img0 = new QueryWrapper<>();
                img0.eq("fire_work_id", fireWork.getId());
                img0.orderByAsc("img_type");
                List<FireWorkImg> imgs = fireWorkImgService.list(img0);
                if(CollUtil.isNotEmpty(imgs)){
                    for (FireWorkImg img : imgs){
                        img.setImgUrl(imgPrefix + img.getImgUrl());
                    }
                }
                fireWork.setImgList(imgs);

            }
            map.put("fireWork",fireWork);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);

        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  作业票列表
     * @param
     * @throws Exception
     */
    @PostMapping(value = "/my/list")
    public JSONObject myRegList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            logBefore(logger, "fire/work/my/list 接收的参数： "+requestParam);
            System.out.println("fire/work/my/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int record_type = jsonRequest.containsKey("record_type") ? jsonRequest.getInt("record_type") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex") ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 10;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            SysUser sysUser = sysUserService.selectByUniqueColumn("user_id",user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您没有该权限"),true,true);
            }


            Shop shop = shopService.findById(user.getShopId());
            if(shop != null && shop.getState() == 0){
                System.out.println(shop.getShopName() + " 企业已被禁用");
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
            }

            map.put("isOpenFirework",sysUser.getIsOpenFirework());
            if(sysUser.getIsOpenFirework() == 0){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"模块未开启", map),true,false);
            }

            QueryWrapper<FireWork> qw = new QueryWrapper<>();
            if(user.getIsTest() == 0){
                if(sysUser.getUserType() < 2) {

                } else if(sysUser.getUserType() == 2){
                    qw.eq("group_id", sysUser.getGroupId());
                } else if(sysUser.getUserType() == 3){
                    qw.eq("pianqu_id", sysUser.getPianquId());
                }else{
                    qw.eq("reg_company_id", sysUser.getShopId());
                }
            }
            qw.eq("record_type",record_type);
            qw.orderByDesc("create_time");

            List<FireWork> list = fireWorkService.getPageEntityList(qw, pageIndex, pageSize);
            for (FireWork fireWork : list){
                fireWork.setIsSafeUser(0);
                fireWork.setIsHeaderUser(0);
                FireWorkUser user1 = fireWorkUserService.getUserBySysUserId(fireWork.getId(), sysUser.getUserId());
                if(user1 != null){
                    fireWork.setIsCanRegDevice(1);
                }

                fireWork.setIsHasDeviceReg(0);
                QueryWrapper<DeviceWeldingRecord> qwFireWork = new QueryWrapper<>();
                qwFireWork.eq("fire_work_id", fireWork.getId());
                qwFireWork.last("limit 1");
                DeviceWeldingRecord weldingRecord = deviceWeldingRecordService.getOne(qwFireWork);
                if(weldingRecord!= null){
                    fireWork.setIsHasDeviceReg(1);
                    fireWork.setIsReback(weldingRecord.getState() == 2? 1 : 0);
                    fireWork.setDeviceNum(weldingRecord.getDeviceNum());
                }


                if(fireWork.getFireEndTime()!= null){
                    //{天, 时, 分, 秒}
                    long[] times = DateUtil.getDistanceTimes(fireWork.getFireBeginTime(),fireWork.getFireEndTime());
                    String workTimes = "";
                    if(times[0] > 0){
                        workTimes += times[0] + "天";
                    }
                    if(times[1] > 0){
                        workTimes += times[1] + "小时";
                    }
                    if(times[2] > 0){
                        workTimes += times[2] + "分钟";
                    }
                    fireWork.setWorkTimes(workTimes);
                }

                if(fireWork.getSafeSysUserId() != null){
                    if(fireWork.getSafeSysUserId().intValue() == sysUser.getUserId().intValue()){
                        fireWork.setIsSafeUser(1);
                    }
                }
                fireWork.setSignType(0);
                //动火作业票
                if(fireWork.getRecordType() == 0){
                    if(fireWork.getOpLevel() == 1){//非生产区域作业票  只是生产经理处理
                        //生产经理
                        if(fireWork.getLastCheckSysUserId() != null && fireWork.getLastCheckSysUserId().intValue() == sysUser.getUserId().intValue()){
                            fireWork.setSignType(1);
                        }
                    }else{//生产作业票
                        //生产经理
                        if(fireWork.getLastCheckSysUserId() != null && fireWork.getLastCheckSysUserId().intValue() == sysUser.getUserId().intValue()){
                            fireWork.setSignType(1);
                        }

                        //片区经理审批
                        if(fireWork.getLastSubmitSysUserId() != null && fireWork.getLastSubmitSysUserId().intValue() == sysUser.getUserId().intValue()){
                            fireWork.setSignType(2);
                        }
                    }
                } else if(fireWork.getRecordType() == 2 || fireWork.getRecordType() == 1){
                    //生产经理
                    if(fireWork.getLastCheckSysUserId() != null && fireWork.getLastCheckSysUserId().intValue() == sysUser.getUserId().intValue()){
                        fireWork.setSignType(1);
                    }
                }

                fireWork.setCheckSignState(0);
                if(fireWork.getLastCheckTime() != null){
                    fireWork.setCheckSignState(1);
                }
                fireWork.setSubmitSignState(0);
                if(fireWork.getLastSubmitTime() != null){
                    fireWork.setSubmitSignState(1);
                }

                fireWork.setIsInRegTime(0);
                if(fireWork.getFireBeginTime().getTime() < new Date().getTime() && new Date().getTime() < fireWork.getFireEndTime().getTime()){
                    fireWork.setIsInRegTime(1);
                }
            }

            map.put("records",list);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),map),false,false);

        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  添加作业动火分析
     * @param
     * @throws Exception
     */
    @PostMapping(value="/add/analysis")
    public JSONObject addAnalysis(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;

        logBefore(logger, "fire/work/add/analysis 接收的参数： "+requestParam);
        System.out.println("fire/work/add/analysis 接收的参数： "+requestParam);
        JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
        int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
        LockInfo lockInfo = lockTemplate.lock(user_id + "_addAnalysis", 30000L, 5000L, RedissonLockExecutor.class);
        if (lockInfo == null) {
            return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"业务处理中,请稍后再试"),true,true);
        }

        try{
            int workId = jsonRequest.containsKey("work_id") ? jsonRequest.getInt("work_id") : 0;
            String analysis = jsonRequest.containsKey("analysis") ? jsonRequest.getStr("analysis") : null;


            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }


            Shop shop = shopService.findById(user.getShopId());
            if(shop.getState() == 0){
                System.out.println(shop.getShopName() + " 企业已被禁用");
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
            }

            SysUser sysUser = sysUserService.selectByUniqueColumn("user_id",user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您没有该权限"),true,true);
            }

            FireWorkAnalysis workAnalysis = JSONUtil.toBean(analysis, FireWorkAnalysis.class);

            workAnalysis.setCreateTime(new Date());
            workAnalysis.setState(0);
            boolean ret = workAnalysisService.save(workAnalysis);
            if(ret){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"添加成功"),true,true);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"成功"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }finally {
            //释放锁
            lockTemplate.releaseLock(lockInfo);
        }
        return result;
    }

    /**
     *  处理巡查安全措施
     * @param
     * @throws Exception
     */
    @PostMapping(value="/check/measures")
    public JSONObject checkMeasures(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;

        logBefore(logger, "fire/work/check/measures 接收的参数： " + requestParam);
        System.out.println("fire/work/check/measures 接收的参数： " + requestParam);
        JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
        int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
        LockInfo lockInfo = lockTemplate.lock(user_id + "_checkAnalysis", 30000L, 5000L, RedissonLockExecutor.class);
        if (lockInfo == null) {
            return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"业务处理中,请稍后再试"),true,true);
        }

        try{
            int workId = jsonRequest.containsKey("work_id") ? jsonRequest.getInt("work_id") : 0;
            String measures = jsonRequest.containsKey("measures") ? jsonRequest.getStr("measures") : null;
            String user_type = jsonRequest.containsKey("user_type") ? jsonRequest.getStr("user_type") : null;
            String sign_img = jsonRequest.containsKey("sign_img") ? jsonRequest.getStr("sign_img") : null;


            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }


            Shop shop = shopService.findById(user.getShopId());
            if(shop.getState() == 0){
                System.out.println(shop.getShopName() + " 企业已被禁用");
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
            }

            SysUser sysUser = sysUserService.selectByUniqueColumn("user_id",user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您没有该权限"),true,true);
            }


            FireWork fireWork = fireWorkService.findById(workId);
            if(fireWork != null){
                if(StrUtil.isNotEmpty(user_type) && user_type.equals("safe")){
                    fireWork.setSafeSignImg(sign_img);
                }else if(StrUtil.isNotEmpty(user_type) && user_type.equals("header")){
                    fireWork.setHeaderSignImg(sign_img);
                }
            }


            List<FireWorkMeasures> workAnalysis = JSONUtil.toList(measures, FireWorkMeasures.class);

            int ret = workMeasuresService.checkMeasures(user,fireWork,sysUser,workAnalysis);
            if(ret > 0){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"处理成功"),true,true);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"成功"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }finally {
            //释放锁
            lockTemplate.releaseLock(lockInfo);
        }
        return result;
    }

    /**
     *  最后审核人员处理
     * @param
     * @throws Exception
     */
    @PostMapping(value="/lastCheck")
    public JSONObject lastCheck(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        logBefore(logger, "fire/work/lastCheck 接收的参数： " + requestParam);
        System.out.println("fire/work/lastCheck 接收的参数： " + requestParam);
        JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
        int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
        LockInfo lockInfo = lockTemplate.lock(user_id + "_lastCheck", 30000L, 5000L, RedissonLockExecutor.class);
        if (lockInfo == null) {
            return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"业务处理中,请稍后再试"),true,true);
        }

        try{
            int workId = jsonRequest.containsKey("work_id") ? jsonRequest.getInt("work_id") : 0;
            int checkState = jsonRequest.containsKey("check_state") ? jsonRequest.getInt("check_state") : 0;
            int isSubmit = jsonRequest.containsKey("is_submit") ? jsonRequest.getInt("is_submit") : 0;
            String result_content = jsonRequest.containsKey("result_content") ? jsonRequest.getStr("result_content") : null;
            String sign_img = jsonRequest.containsKey("sign_img") ? jsonRequest.getStr("sign_img") : null;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }


            Shop shop = shopService.findById(user.getShopId());
            if(shop.getState() == 0){
                System.out.println(shop.getShopName() + " 企业已被禁用");
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
            }

            SysUser sysUser = sysUserService.selectByUniqueColumn("user_id",user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您没有该权限"),true,true);
            }

            FireWork fireWork = fireWorkService.findById(workId);
            if(fireWork == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该作业票不存在"),true,true);
            }

            if(StrUtil.isNotEmpty(sign_img)){
                if(isSubmit == 0){
                    fireWork.setCheckSignImg(sign_img);
                }else{
                    fireWork.setSubmitSignImg(sign_img);
                }
            }

            if(isSubmit == 0) {//生产经理审批
                if (sysUser.getUserId().intValue() != fireWork.getLastCheckSysUserId().intValue()) {
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "您没有审核权限"), true, true);
                }
            }else {//片区经理审批
                if (sysUser.getUserId().intValue() != fireWork.getLastSubmitSysUserId().intValue()) {
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "您没有审核权限"), true, true);
                }
            }

            FsrDevice fsrDevice = null;
            DeviceWelding device = null;
            QueryWrapper<DeviceWeldingRecord> qwRecord = new QueryWrapper<>();
            qwRecord.eq("fire_work_id", fireWork.getId());
            qwRecord.last("limit 1");
            DeviceWeldingRecord weldingRecord = deviceWeldingRecordService.getOne(qwRecord);
            if(weldingRecord != null){
                device = deviceWeldingService.findById(weldingRecord.getDeviceId());
                if(device != null){
                    if(device.getIsHasBreaker() == 1) {
                        fsrDevice = fsrDeviceService.findById(device.getFsrBreakerId());
                    }
                }
            }


            //当前可以处理审核
            if(fireWork.getState() == 1){
                if(fireWork.getRecordType() == 0){

                    // 1 - 非生产  2 -  生产
                    if(fireWork.getOpLevel() == 1){
                        if(checkState == 1){
                            fireWork.setState(2);//同意
                        }else{
                            fireWork.setState(4);//驳回
                        }
                        fireWork.setLastCheckState(checkState);
                        fireWork.setLastCheckTime(new Date());
                        fireWork.setLastCheckResult(result_content);

                        //审批完成  同步要审批 焊机申请状态为2
                        if(weldingRecord != null){
                            if(device != null && device.getIsHasBreaker() == 1){
                                if(checkState == 1){
                                    device.setUseState(2);//同意
                                }else{
                                    device.setUseState(4);//驳回
                                }
                                deviceWeldingService.updateById(device);

                                if(checkState == 1 && fsrDevice != null && fsrDevice.getOnlineState() == 1){
                                    //合闸
                                    fsrDeviceService.commandOp(fsrDevice,1);
                                }
                            }

                            weldingRecord.setCheckSysUserId(sysUser.getUserId());
                            weldingRecord.setDepartCheckUserName(sysUser.getName());
                            if(checkState == 1) {
                                weldingRecord.setDepartCheckState(1);
                                weldingRecord.setDepartCheckResult("审核通过");
                            }else{
                                weldingRecord.setDepartCheckState(2);
                                weldingRecord.setDepartCheckResult("审核驳回");
                            }
                            weldingRecord.setDepartCheckTime(new Date());
                            deviceWeldingRecordService.updateById(weldingRecord);
                        }
                    }else if(fireWork.getOpLevel() == 2){//生产
                        if(isSubmit == 1 && fireWork.getLastCheckTime()!= null){
                            fireWork.setLastSubmitState(checkState);
                            fireWork.setLastSubmitTime(new Date());
                            fireWork.setLastSubmitResult(result_content);
                            if(checkState == 1){
                                fireWork.setState(2);//同意
                            }else{
                                fireWork.setState(4);//驳回
                            }
                            //审批完成  同步要审批 焊机申请状态为2
                            if(weldingRecord != null){
                                if(device != null && device.getIsHasBreaker() == 1){
                                    if(checkState == 1){
                                        device.setUseState(2);//同意
                                    }else{
                                        device.setUseState(4);//驳回
                                    }
                                    deviceWeldingService.updateById(device);
                                    if(checkState == 1 && fsrDevice != null && fsrDevice.getOnlineState() == 1){
                                        //合闸
                                        fsrDeviceService.commandOp(fsrDevice,1);
                                    }
                                }
                                weldingRecord.setCheckSysUserId(sysUser.getUserId());
                                weldingRecord.setDepartCheckUserName(sysUser.getName());
                                if(checkState == 1) {
                                    weldingRecord.setDepartCheckState(1);
                                    weldingRecord.setDepartCheckResult("审核通过");
                                }else{
                                    weldingRecord.setDepartCheckState(2);
                                    weldingRecord.setDepartCheckResult("审核驳回");
                                }
                                weldingRecord.setDepartCheckTime(new Date());
                                deviceWeldingRecordService.updateById(weldingRecord);
                            }

                        }else{
                            fireWork.setLastCheckState(checkState);
                            fireWork.setLastCheckTime(new Date());
                            fireWork.setLastCheckResult(result_content);
                        }
                    }
                }else{
                    if(checkState == 1){
                        fireWork.setState(2);//同意
                    }else{
                        fireWork.setState(4);//驳回
                    }
                    fireWork.setLastCheckState(checkState);
                    fireWork.setLastCheckTime(new Date());
                    fireWork.setLastCheckResult(result_content);
                }

                boolean bl = fireWorkService.updateById(fireWork);
                if(bl){
                    //
                    if(fireWork.getRecordType() == 0){
                        if(isSubmit == 0 && device.getIsSafe() == 0) {//生产经理审批完，要给片区经理推送消息
                            wxTemplateService.sendWxMsgUseDeviceToPianqu(weldingRecord, device);
                        }
                    }else if(fireWork.getRecordType() == 2){
                        wxTemplateService.sendWxMsgFireworkToSafe(fireWork);
                    }
                    if(checkState == 1){
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"审核成功"),true,true);
                    }else{
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"驳回成功"),true,true);
                    }
                }else{
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该作业票不存在"),true,true);
                }
            }
            return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前不能审核"),true,true);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }finally {
            //释放锁
            lockTemplate.releaseLock(lockInfo);
        }
        return result;
    }

    /**
     *  完工验收操作
     * @param
     * @throws Exception
     */
    @PostMapping(value="/checkAccept")
    public JSONObject checkAccept(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        logBefore(logger, "fire/work/checkAccept 接收的参数： " + requestParam);
        System.out.println("fire/work/checkAccept 接收的参数： " + requestParam);
        JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
        int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
        LockInfo lockInfo = lockTemplate.lock(user_id + "_checkAccept", 30000L, 5000L, RedissonLockExecutor.class);
        if (lockInfo == null) {
            return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"业务处理中,请稍后再试"),true,true);
        }
        try{
            int workId = jsonRequest.containsKey("work_id") ? jsonRequest.getInt("work_id") : 0;
            String sign_img = jsonRequest.containsKey("sign_img") ? jsonRequest.getStr("sign_img") : null;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }


            Shop shop = shopService.findById(user.getShopId());
            if(shop.getState() == 0){
                System.out.println(shop.getShopName() + " 企业已被禁用");
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
            }


            SysUser sysUser = sysUserService.selectByUniqueColumn("user_id", user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您没有该权限"),true,true);
            }

            FireWork fireWork = fireWorkService.findById(workId);
            if(fireWork == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该作业票不存在"),true,true);
            }

            if(StrUtil.isNotEmpty(sign_img)){
                fireWork.setCheckAcceptSignImg(sign_img);
            }

            if (sysUser.getUserId().intValue() != fireWork.getSafeSysUserId().intValue()) {
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "您没有权限"), true, true);
            }

            //当前可以处理审核
            if(fireWork.getState() == 2){
                if(fireWork.getRecordType() == 0) {
                }
                fireWork.setState(3);
                fireWork.setCheckAcceptTime(new Date());
                boolean bl = fireWorkService.updateById(fireWork);
                if(bl){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"验收成功"),true,true);
                }else{
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该作业票不存在"),true,true);
                }
            }
            return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前不能结束完工"),true,true);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }finally {
            //释放锁
            lockTemplate.releaseLock(lockInfo);
        }
        return result;
    }

    /**
     * 上传签名
     * @param
     * @throws Exception
     */
    @PostMapping(value="/uploadSign")
    @ResponseBody
    public JSONObject uploadSign(HttpServletRequest request) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();

        try{
            // 创建一个通用的多部分解析器.
            CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            // 设置编码
            commonsMultipartResolver.setDefaultEncoding("utf-8");
            // 判断是否有文件上传
            if (commonsMultipartResolver.isMultipart(request)) {//有文件上传
                //将request变成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
                //获取multiRequest 中所有的文件名
                Iterator<String> iter = multiRequest.getFileNames();
                if (iter.hasNext()) {
                    Map<String, MultipartFile> maps = multiRequest.getFileMap();
                    for(String key : maps.keySet()) {
                        MultipartFile certurl = maps.get(key);
                        if (!certurl.isEmpty()) {
                            String prefix = certurl.getOriginalFilename().substring(certurl.getOriginalFilename().lastIndexOf(".") + 1);
                            if ("jpeg".equals(prefix) || "jpg".equals(prefix) || "png".equals(prefix)) {
                                String fileName = "record_img_" + new Date().getTime() + "." + prefix;// user_photo.getOriginalFilename();
                                try {
                                    byte[] byteImg = certurl.getBytes();
                                    if (byteImg != null) {
                                        //上传头像到OSS
                                        int upload_type = OssUtil.TYPE_FIRE_WORK_SIGN_PHOTOS;
                                        String filePath1 = OssUtil.getUploadPrefix(upload_type) + DateUtil.getMonthStr(new Date());

                                        String img_key = filePath1 + "/" + fileName;
                                        File file = new File(uploadPath + filePath1);
                                        if(!file.exists()){
                                            file.mkdirs();
                                        }
                                        map.put("file_name", img_key);

                                        String filePath = uploadPath + img_key;
                                        FileOutputStream out = new FileOutputStream(filePath);
                                        out.write(certurl.getBytes());
                                        out.flush();
                                        out.close();

                                    }
                                } catch (IOException e) {
                                    result = Tools.getJson(new GsonResultBean<>(-4, "系统异常"), true, true);
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
            }
            return Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "图片上传成功",map), true, false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.printf(""+e.getMessage());
        }
        return result;
    }

    /**
     * 上传图片
     * @param
     * @throws Exception
     */
    @PostMapping(value="/uploadImg")
    @ResponseBody
    public JSONObject uploadImg(@RequestParam("fire_work_id") int fire_work_id, @RequestParam("img_type") int img_type,
                                HttpServletRequest request) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            // 创建一个通用的多部分解析器.
            CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            // 设置编码
            commonsMultipartResolver.setDefaultEncoding("utf-8");
            // 判断是否有文件上传
            if (commonsMultipartResolver.isMultipart(request)) {//有文件上传
                //将request变成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
                //获取multiRequest 中所有的文件名
                Iterator<String> iter = multiRequest.getFileNames();
                if (iter.hasNext()) {
                    Map<String, MultipartFile> maps = multiRequest.getFileMap();
                    for(String key : maps.keySet()) {
                        MultipartFile certurl = maps.get(key);
                        if (!certurl.isEmpty()) {
                            String prefix = certurl.getOriginalFilename().substring(certurl.getOriginalFilename().lastIndexOf(".") + 1);
                            if ("jpeg".equals(prefix) || "jpg".equals(prefix) || "png".equals(prefix) || "mp4".equals(prefix)) {
                                String fileName = "record_img_" + new Date().getTime() + "." + prefix;// user_photo.getOriginalFilename();
                                try {
                                    byte[] byteImg = certurl.getBytes();
                                    if (byteImg != null) {
                                        //上传头像到OSS
                                        int upload_type = OssUtil.TYPE_FIRE_WORK_SIGN_PHOTOS;
                                        String filePath1 = OssUtil.getUploadPrefix(upload_type) + DateUtil.getMonthStr(new Date());

                                        String img_key = filePath1 + "/" + fileName;
                                        File file = new File(uploadPath + filePath1);
                                        if(!file.exists()){
                                            file.mkdirs();
                                        }
                                        map.put("file_name", img_key);

                                        String filePath = uploadPath + img_key;
                                        FileOutputStream out = new FileOutputStream(filePath);
                                        out.write(certurl.getBytes());
                                        out.flush();
                                        out.close();


                                        FireWorkImg img = new FireWorkImg();
                                        img.setFireWorkId(fire_work_id);
                                        img.setImgType(img_type);
                                        img.setImgUrl(img_key);
                                        img.setPrefix(prefix.toLowerCase());
                                        fireWorkImgService.save(img);
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                    result = Tools.getJson(new GsonResultBean<>(-4, "系统异常"), true, true);
                                }
                            }
                        }
                    }
                }
            }
            return Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "图片上传成功",map), true, false);
        }catch (Exception e) {
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.printf("" + e.getMessage());
        }
        return result;
    }

}
